import { useReducer, useState } from 'react'
import './style.css'
import { products } from './json/products'
const CartTodo = () => {
  const totalPrice = (state) => {
    return state.reduce((pre, item) => pre + item.price * item.count, 0)
  }
  const reducer = (state, { type, payload }) => {
    switch (type) {
      case 'add':
        const findIndex = state.findIndex((item) => item.id === payload)
        if (findIndex !== -1) {
          console.log([...state.slice(0, findIndex)])
          return [...state.slice(0, findIndex), { ...state[findIndex], count: state[findIndex].count + 1 }, ...state.slice(findIndex + 1)]
        } else {
          return [
            ...state,
            {
              ...products.find((p) => p.id === payload),
              count: 1,
            },
          ]
        }
      // 存在加一
      case 'remove':
        let removeData = state.find((item) => item.id === payload)
        console.log(removeData)
        return state.filter((item) => item !== removeData)
      case 'clear':
        return []
      default:
        return state
    }
  }
  const isitState = []
  const [state, dispatch] = useReducer(reducer, isitState)
  console.log(state)
  return (
    <div className="content">
      <div className="left">
        <h2>商品列表</h2>
        <div className="plist">
          {products.map((item) => (
            <div className="item" key={item.id}>
              <div className="title">{item.name}</div>
              <img src={item.image} />
              <div className="price">
                <button className="add-cart-btn" onClick={() => dispatch({ type: 'add', payload: item.id })}>
                  {item.price}元 加入购物车
                </button>
              </div>
            </div>
          ))}
        </div>
      </div>
      <div className="right">
        <h2>
          购物车
          <button className="cart-clr-btn" onClick={() => dispatch({ type: 'clear' })}>
            清空购物车
          </button>
        </h2>
        <div className="cart">
          {state.map((item) => (
            <div className="item" key={item.id}>
              <div className="title">{item.name}</div>
              <img src={item.image} />
              <div className="price">
                <input type="number" style={{ display: 'block', margin: 'auto' }} value={item.count} />
                <button className="add-cart-btn" onClick={() => dispatch({ type: 'remove', payload: item.id })}>
                  {item.price}元 删除
                </button>
              </div>
            </div>
          ))}
        </div>
        <div>
          <h3>
            总价：<span id="total">{parseInt(totalPrice(state))}</span>元
          </h3>
        </div>
      </div>
    </div>
  )
}

export default CartTodo
